package com.hzsk.lisence.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzsk.lisence.entity.*;
import com.hzsk.lisence.entity.query.IDCInfoQuery;
import com.hzsk.lisence.entity.response.IncResponce;
import com.hzsk.lisence.enums.UserRoleEnum;
import com.hzsk.lisence.mapper.EmProducePlanMapper;
import com.hzsk.lisence.mapper.IDCMapper;
import com.hzsk.lisence.mapper.LisenceUserMapper;
import com.hzsk.lisence.service.IDCService;
import com.hzsk.lisence.util.EncipherUtils;
import com.hzsk.lisence.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class IDCServiceImpl implements IDCService {

    private final static String  IDC_WRITE_COMMAND = "IDCWP"; //IDC写入口令
    private final static String  IDC_DEVICE_ID = "IDCDID";//IDC设备ID
    private final static String NOT_WRITTEN = "NOT_WRITTEN";
    private final static String WRITE_SUCCESSFUL = "WRITE_SUCCESSFUL";
    private final static String WRITE_FAILED = "WRITE_FAILED";

    public static RestTemplate restTemplate;
    private final static Integer FLAG_NORMAL = 0;
    private final static Integer FLAG_DISABLE = 1;
    
    @Value("${mes.get-order-code}")
    private String getOrderCodeUrl;

    @Resource
    public IDCMapper idcMapper;

    @Resource
    public LisenceUserMapper lisenceUserMapper;

    @Resource
    public EmProducePlanMapper emProducePlanMapper;

    @Override
    public void checkStaffAuthority(IncResponce incResponce, IDCInfoQuery idcInfoQuery) {
        boolean staffAuthority = false;
        String operatorIdentifying = idcInfoQuery.getOperatorIdentifying();
        if (StringUtils.isNotBlank(operatorIdentifying)) {
            String[] split = operatorIdentifying.split(",");
            if (split.length != 2){
                incResponce.setCode(1);
                incResponce.setData(false);
                incResponce.setErrorMessage("用户无权限！");
                return;
            }
            String userName = split[0];
            String password = split[1];
            String decrypt = EncipherUtils.encrypted(password);
            List<LisenceUserEntity> lisenceUserEntity = lisenceUserMapper.selectIsUserByAccountAndPassword(userName,decrypt);
            if (lisenceUserEntity != null && lisenceUserEntity.size() > 0){
                staffAuthority = true;
            }
        }else {
            incResponce.setCode(1);
            incResponce.setData(staffAuthority);
            incResponce.setErrorMessage("用户无权限！");
        }
        incResponce.setCode(0);
        incResponce.setData(staffAuthority);

    }

    @Override
    public void checkEmUkeyAuthority(IncResponce incResponce, IDCInfoQuery idcInfoQuery){
        boolean emUkeyAuthority = false;
        String emUkey = idcInfoQuery.getEmUkey();
        String emUID = idcInfoQuery.getEmUID();
        if (StringUtils.isNotBlank(emUkey) && StringUtils.isNotBlank(emUID)) {
            EmUkeyEntity emUkeyEntity = idcMapper.checkEmUkey(emUID, emUkey);
            if (emUkeyEntity == null) {
                incResponce.setCode(1);
                incResponce.setData(false);
                incResponce.setErrorMessage("U盾不匹配！");
            }else {
                emUkeyAuthority = true;
            }
        }else {
            incResponce.setCode(1);
            incResponce.setData(false);
            incResponce.setErrorMessage("U盾不匹配!");
        }
        incResponce.setCode(0);
        incResponce.setData(emUkeyAuthority);
    }

    @Override
    public void getIdcWriteCommand(IncResponce incResponce, IDCInfoQuery idcInfoQuery){
        String idcChipId = idcInfoQuery.getIdcChipId();
        String operatorIdentifying = idcInfoQuery.getOperatorIdentifying();
        String emUkey = idcInfoQuery.getEmUkey();
        String emUID = idcInfoQuery.getEmUID();
        IDCEntity idcEntity = idcMapper.selectIsIdcChipId(idcChipId);
        EmUkeyUseEntity emUkeyUseEntity = new EmUkeyUseEntity();
        emUkeyUseEntity.setUseStatus("SUCCESS");
        emUkeyUseEntity.setIdcChipId(idcChipId);
        //校验口令是否生成
        emUkeyUseEntity.setOperator(operatorIdentifying.split(",")[0]);
        if (idcEntity != null){
            incResponce.setCode(1);
            incResponce.setErrorMessage("此IDC口令已生成,请勿重复生成！");
            return;
        }else {
            idcEntity = new IDCEntity();
        }
        //检查U盾是否匹配
        EmUkeyEntity emUkeyEntity = idcMapper.checkEmUkey(emUID, emUkey);
        if (emUkeyEntity == null) {
            emUkeyUseEntity.setUseStatus("FAIL");
            idcMapper.saveEmUkeyUseInfo(emUkeyUseEntity);
            incResponce.setCode(1);
            incResponce.setData(false);
            incResponce.setErrorMessage("U盾不匹配!");
            return;
        }
        //根据IDC芯片ID获取IDC生产计划工单号
        String orderId = getOrderCode(idcChipId);
        System.err.println(orderId);
        //是否为指定订单排班计划，是否为超过IDC制作上限
        if (StringUtils.isBlank(orderId)) {
            emUkeyUseEntity.setUseStatus("FAIL");
            idcMapper.saveEmUkeyUseInfo(emUkeyUseEntity);
            incResponce.setCode(1);
            incResponce.setData(false);
            incResponce.setErrorMessage("流水号不匹配!请重新扫码！");
            return;
        }else {
            Integer integer = idcMapper.selectIDCByStatusAndPlanId(orderId);
            EmProducePlanEntity emProducePlanEntity = emProducePlanMapper.selectProducePlanByOrderCode(orderId);
            Integer quantity = emProducePlanEntity.getQuantity();
            String estDate = emProducePlanEntity.getEstDate();
            String latDate = emProducePlanEntity.getLatDate();
            Date currentDate = new Date();
            Date startDate = new Date();
            Date endDate = new Date();
            try {
                // 解析开始时间与结束时间
                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                 startDate = sdf.parse(estDate);
                 endDate = sdf.parse(latDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String operatorCode = emProducePlanEntity.getOperatorCode();
            String[] split = operatorIdentifying.split(",");
            String userName = split[0];
            String password = split[1];
            String decrypt = EncipherUtils.encrypted(password);
            LisenceUserEntity lisenceUserEntity = lisenceUserMapper.selectIsUserByAccountAndPasswordByOneAndCode(userName,decrypt,operatorCode);
            if (lisenceUserEntity == null ||   !(currentDate.compareTo(startDate) >= 0 && currentDate.compareTo(endDate) <= 0)){
                emUkeyUseEntity.setUseStatus("FAIL");
                idcMapper.saveEmUkeyUseInfo(emUkeyUseEntity);
                incResponce.setCode(1);
                incResponce.setErrorMessage("账号无权限！");
                return;
            }
            idcEntity.setOperatorName(lisenceUserEntity.getUserName());
            if (integer > quantity){
                emUkeyUseEntity.setUseStatus("FAIL");
                idcMapper.saveEmUkeyUseInfo(emUkeyUseEntity);
                incResponce.setCode(1);
                incResponce.setData(false);
                incResponce.setErrorMessage("已超过当前订单IDC制作上限！");
                return;
            }
        }
        idcEntity.setProducePlanId(orderId);
        emUkeyUseEntity.setEmUkeyId(emUkeyEntity.getId());
        emUkeyUseEntity.setIdcStatus(NOT_WRITTEN);
        emUkeyUseEntity.setId(emUkeyEntity.getId());
        //根据生产计划校验用户信息
        if (StringUtils.isBlank(operatorIdentifying) || operatorIdentifying.split(",").length != 2){
            incResponce.setCode(1);
            incResponce.setErrorMessage("参数异常");
            return;
        }
        //保存使用记录
        idcMapper.saveEmUkeyUseInfo(emUkeyUseEntity);
        String idcwp = this.getIDCWP();
        idcEntity.setIdcChipId(idcChipId);
        idcEntity.setIdcStatus(NOT_WRITTEN);
        idcEntity.setIdcWriteCommand(idcwp);
        idcEntity.setOperatorIdentifying(operatorIdentifying);
        idcEntity.setFlag(FLAG_NORMAL);
        idcMapper.add(idcEntity);
        incResponce.setCode(0);
        incResponce.setData(idcwp);
    }

    @Override
    public void getWriteCommandByChipId(IncResponce incResponce, IDCInfoQuery idcInfoQuery) {
        String idcWriteCommand = idcInfoQuery.getIdcWriteCommand();
        String idcChipId = idcInfoQuery.getIdcChipId();
        IDCEntity idcEntity = idcMapper.selectIsWriteCommandAndIdcChipId(idcChipId,idcWriteCommand);
        if (idcEntity == null){
            incResponce.setCode(1);
            incResponce.setErrorMessage("写入口令与IDC芯片ID不符！设备ID生成失败！");
        }else {
            String idcdid = getIDCDID();
            idcEntity.setIdcDeviceId(idcdid);
            idcMapper.updateIDCEntity(idcEntity);
            incResponce.setCode(0);
            incResponce.setData(idcdid);
        }
    }

    @Override
    public void updateIDCStatus(IncResponce incResponce, IDCInfoQuery idcInfoQuery) {
        String idcChipId = idcInfoQuery.getIdcChipId();
        String idcDeviceId = idcInfoQuery.getIdcDeviceId();
        String idcStatus = idcInfoQuery.getIdcStatus();
        if (idcStatus.equalsIgnoreCase(WRITE_FAILED)){
            idcMapper.delIDCEntityByChipId(idcChipId);
            idcMapper.updateEmUkeyUseStatus(idcChipId,WRITE_FAILED);
            incResponce.setCode(0);
            incResponce.setData("操作成功");
            return;
        }
        if (StringUtils.isBlank(idcChipId) || StringUtils.isBlank(idcDeviceId) || StringUtils.isBlank(idcStatus)){
            incResponce.setCode(1);
            incResponce.setErrorMessage("请求参数异常！");
        }else {
            IDCEntity idcEntity = idcMapper.selectIsWrDeviceIdAndIdcChipId(idcChipId, idcDeviceId);
            if (idcEntity == null) {
                incResponce.setCode(0);
                incResponce.setErrorMessage("IDC参数有误！");
            }else {
                idcEntity.setIdcStatus(idcStatus);
                idcEntity.setIdcDeviceId(idcDeviceId);
                idcEntity.setIdcChipId(idcChipId);
                idcMapper.updateIDCEntityStatus(idcEntity);
                idcMapper.updateEmUkeyUseStatus(idcChipId,WRITE_SUCCESSFUL);
                incResponce.setCode(0);
                incResponce.setData("操作成功");
            }
        }
    }

    @Override
    public void getIDCInfoByProducePlan(IncResponce incResponce, IDCInfoQuery idcInfoQuery) {
        PageHelper.startPage(idcInfoQuery.getPageNum(), idcInfoQuery.getPageSize());
        Integer userId = idcInfoQuery.getUserId();
        LisenceUserEntity entity = lisenceUserMapper.selectEntityById(userId);
        if (entity == null) {
            incResponce.setData("用户不存在");
            incResponce.setCode(1);
            return;
        } else if (!UserRoleEnum.PRODUCE_MANAGER.getCode().equalsIgnoreCase(entity.getUserRole())){
            String userInfo = entity.getUserAccount() + "," +  EncipherUtils.decrypt(entity.getPassword());
            idcInfoQuery.setOperatorIdentifying(userInfo);
        }

        List<IDCEntity> infos =  idcMapper.getIDCInfoByProducePlan(idcInfoQuery);
        incResponce.setData(new PageInfo<>(infos));
        incResponce.setCode(0);
    }

    @Override
    public void getemUKeyUseInfo(IncResponce incResponce, IDCInfoQuery idcInfoQuery) {
        Integer userId = idcInfoQuery.getUserId();
        LisenceUserEntity entity = lisenceUserMapper.selectEntityById(userId);
        if (entity == null) {
            incResponce.setData("用户不存在");
            incResponce.setCode(1);
            return;
        }else if (!UserRoleEnum.PRODUCE_MANAGER.getCode().equalsIgnoreCase(entity.getUserRole())){
            idcInfoQuery.setOperatorIdentifying(entity.getUserAccount());
        }
        PageHelper.startPage(idcInfoQuery.getPageNum(), idcInfoQuery.getPageSize());
        List<EmUkeyUseEntity> infos =  idcMapper.getEmUkeyUseInfo(idcInfoQuery);
        PageInfo<EmUkeyUseEntity> pageInfo = new PageInfo<>(infos);
        incResponce.setData(pageInfo);
        incResponce.setCode(0);
    }

    @Override
    public IDCEntity getIdcEntityByIdcDeviceId(String idcDeviceId) {
        return idcMapper.selectIdcChipIdByIdcDeviceId(idcDeviceId);
    }


    private String getIDCWP(){
        String IDCWP = EncipherUtils.encrypted(IDC_WRITE_COMMAND + ":" + UUID.randomUUID().toString().replace("-", "").substring(0, 26));
        System.err.println(IDCWP.length());
        return IDCWP;
    }

    private String getIDCDID(){
        String IDCDID = EncipherUtils.encrypted(IDC_DEVICE_ID + ":" + UUID.randomUUID().toString().replace("-", "").substring(0, 25));
        System.err.println(IDCDID.length());
        return IDCDID;
    }
    
    private String getOrderCode(String idcChipId){
        //调用MES接口，根据IDC编号查询订单号
        if (restTemplate == null){
            restTemplate = new RestTemplate();
        }
        String orderCode = null;
        String resultStr = restTemplate.getForObject(getOrderCodeUrl + "?productCode=" + idcChipId, String.class);
        Map<String, Object> map = JSON.parseObject(resultStr, new TypeReference<Map<String, Object>>(){});
        if (!ObjectUtils.isEmpty(map) && !ObjectUtils.isEmpty(map.get("success"))){
            boolean success = (boolean) map.get("success");
            if (success && !ObjectUtils.isEmpty(map.get("info"))){
                orderCode = (String) map.get("info");
            }
        }
        return orderCode;
    }



}
